//
//  JFImagePickerViewCell.m
//  JFImagePickerController
//
//  Created by Johnil on 15-7-3.
//  Copyright (c) 2015年 Johnil. All rights reserved.
//

#import "JFImagePickerViewCell.h"
#import "JFAssetHelper.h"
#define kIndexPath  dict[@"indexpath"]
#define kLocation   dict[@"location"]
@implementation JFImagePickerViewCell {
	UIView *placeholder;
    UIButton *cicleButton;
    }

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
		_imageView = [[UIImageView alloc] initWithFrame:self.bounds];
		_imageView.contentMode = UIViewContentModeScaleAspectFill;
		_imageView.clipsToBounds = YES;
		[self addSubview:_imageView];
        
        cicleButton=[[UIButton alloc] init] ;
        cicleButton.frame=CGRectMake(self.frame.size.width-30, 4, 26, 26);
        cicleButton.layer.cornerRadius = 13;
        cicleButton.clipsToBounds = YES;

//        cicleButton.layer.borderColor = [UIColor whiteColor].CGColor;
//        cicleButton.layer.borderWidth = 1;
        [self addSubview:cicleButton];
        [cicleButton setBackgroundImage:[UIImage imageNamed:JFSelectedImageName] forState:UIControlStateSelected];
          [cicleButton setBackgroundImage:[UIImage imageNamed:JFUnselectedImageName] forState:UIControlStateNormal];
        
        [cicleButton addTarget:self action:@selector(selectPhoto:) forControlEvents:UIControlEventTouchUpInside];
      
		UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapCell:)];
		[self addGestureRecognizer:tap];
    
    }
    return self;
}
- (void)selectOfNum:(NSInteger)num{
 
    if (num!=-1) {

        //选中
        cicleButton.selected=YES;

		cicleButton.transform = CGAffineTransformMakeScale(.5, .5);
		[UIView animateWithDuration:.3 delay:0 usingSpringWithDamping:.5 initialSpringVelocity:.5 options:UIViewAnimationOptionCurveEaseInOut animations:^{
			cicleButton.transform = CGAffineTransformIdentity;
		} completion:nil];

	} else {
          cicleButton.selected=NO;
	}
}


- (void)removeFromSuperview{
	[[NSNotificationCenter defaultCenter] removeObserver:self];
	[super removeFromSuperview];
}

- (void)reloadNum:(NSNotification *)notifi{
	for (NSDictionary *temp in ASSETHELPER.selectdPhotos) {
//          NSLog(@"%@-current--%@-----%ld",[temp allValues],[temp allValues],(long)ASSETHELPER.currentGroupIndex);
		if ([[[temp allKeys] firstObject] isEqualToString:[NSString stringWithFormat:@"%ld-%ld", (long)_indexPath.row, (long)ASSETHELPER.currentGroupIndex]]) {
			_numOfSelect.text = [[[temp allValues] firstObject] stringValue];
		}
	}
   
}


-(void)selectPhoto:(UIButton *)button
{
   
    if (button.selected==NO) {
        //未选中-->选中
        if (ASSETHELPER.selectdAssets.count+ASSETHELPER.currentPhotosCount==JFMaxPhotosNumber ) {
            NSString *str=   [NSString stringWithFormat:@"最多只能选择%d张图片",JFMaxPhotosNumber ];
            [NSObject showHudTipStr:str];
            return;
        }
        else{
            button.transform = CGAffineTransformMakeScale(.5, .5);
            [UIView animateWithDuration:.3 delay:0 usingSpringWithDamping:.5 initialSpringVelocity:.5 options:UIViewAnimationOptionCurveEaseInOut animations:^{
                button.transform = CGAffineTransformIdentity;
            } completion:nil];
            [ASSETHELPER.selectdAssets addObject:[ASSETHELPER getAssetAtIndex:_indexPath.row]];
        //将位置用数组记录下来 (indexpath的位置和在数组中位置！！！！！！)
            
            [ASSETHELPER.selectdPhotos addObject:@{@"indexpath":@(_indexPath.row),@"location":@(ASSETHELPER.selectdAssets.count-1)}];
            button.selected=YES;
            
        }
        
    }
else if (button.selected==YES)
{
   
    //选中-->取消选中
   __block NSInteger index,value;
   
    //
    [ASSETHELPER.selectdPhotos enumerateObjectsUsingBlock:^(NSDictionary *dict, NSUInteger idx, BOOL * _Nonnull stop) {
//         NSLog(@"%@--%d",dict[@"indexpath"],_indexPath.row);
         if ([dict[@"indexpath"] intValue] == _indexPath.row)
         {
             
               button.selected=NO;
             index=[ASSETHELPER.selectdPhotos indexOfObject:dict];
             [ASSETHELPER.selectdAssets removeObjectAtIndex:[kLocation intValue]];
              [ASSETHELPER.selectdPhotos removeObjectAtIndex:idx ];
              *stop=YES;//停止遍历
          }
    }];
    
    [ASSETHELPER.selectdPhotos enumerateObjectsUsingBlock:^(NSDictionary *dict, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([kLocation intValue]>=index)
        {
             //重新排序   //重新设置location 让后面的成员补位！！
            [ASSETHELPER.selectdPhotos replaceObjectAtIndex:idx withObject:@{@"indexpath":dict[@"indexpath"],@"location":@(index)}];
            index++;
          
        }
    }];
  }
    [[NSNotificationCenter defaultCenter] postNotificationName:@"selectdPhotos" object:nil];
    
    
}



- (void)tapCell:(UITapGestureRecognizer *)tap{
        //预览图片
		[[NSNotificationCenter defaultCenter] postNotificationName:@"showNormalPhotoBrowser" object:_indexPath];

}

@end
